import { messages } from "share/common";
import React, { Component } from "react";
import { Form, Input, Row, Col, Checkbox, Card, Badge, Button, Icon, InputNumber } from "antd";
import "styles/supplier-management/airline-config/platform-common.scss";

const FormItem = Form.Item;

@Form.create()
class AirCardForm extends Component {
  constructor(props) {
    super(props);
    this.state = {
      value: {}, // 初始值
      phone: [], // 客服电话
      email: [], // 客服邮箱
    };
  }

  componentWillMount() {
    const { value, expand } = this.props;
    const phone = value.servicePhone ? value.servicePhone.split(",") : [""];
    const email = value.serviceEmail ? value.serviceEmail.split(",") : [""];
    this.setState({ value, phone, email, expand });
  }

  onInputFormChange = () => {
    setTimeout(() => {
      this.props.form.validateFieldsAndScroll((err, values) => {
        if (!err) {
          this.resetValue(values);
        }
      });
    });
  };

  resetValue = (values) => {
    const { value } = this.state;
    const numbers = [];
    const emails = [];
    for (const key in values) {
      // 筛选出客服电话
      if (key.includes("serverPhone")) {
        numbers.push(values[key]);
      }
    }
    for (const key in values) {
      // 筛选出客服邮箱
      if (key.includes("serverEmail")) {
        emails.push(values[key]);
      }
    }
    const strAccount = {};
    for (const key in value.account) {
      // 筛选出基础字段
      strAccount[key] = values[key] || "";
    }
    value.account = strAccount;
    value.servicePhone = numbers.join(",");
    value.serviceEmail = emails.join(",");
    value.isEnabled = values.enableDomestic || values.enableInternationalRfp;
    value.enableDomestic = values.enableDomestic;
    value.enableInternationalRfp = values.enableInternationalRfp;
    value.qualityWeightCoefficient = values.qualityWeightCoefficient;

    this.setState({ value, email: emails, phone: numbers });
    this.onChange(value);
  };

  onChange = (result) => {
    const { onChange } = this.props;
    onChange && onChange(result);
  };

  commonTitle = (isOpen, title) => (
    <div className="supplier-head-title" onClick={this.expandOrHide}>
      <h3 style={{ display: "inline" }}>{title}</h3>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
      {isOpen ? (
        <Badge status="success" text={messages("supplier-1.key351") /* 已启用*/} />
      ) : (
        <Badge status="default" text={messages("supplier-1.key124") /* 未启用*/} />
      )}
      <a style={{ float: "right" }}>
        {this.state.expand ? messages("common.fold") /*收起*/ : messages("supplier-1.key742") /*展开*/}
      </a>
    </div>
  );

  expandOrHide = () => {
    this.setState({ expand: !this.state.expand });
  };

  onAddPhoneNumber = (index) => {
    const { phone } = this.state;
    if (index === 0) {
      phone.push("");
      this.setState({ phone });
    } else {
      phone.splice(index, 1);
      this.setState({ phone }, () => {
        const values = this.props.form.getFieldsValue();
        this.resetValue(values);
      });
    }
  };

  onAddEmail = (index) => {
    const { email } = this.state;
    if (index === 0) {
      email.push("");
      this.setState({ email });
    } else {
      email.splice(index, 1);
      this.setState({ email }, () => {
        const values = this.props.form.getFieldsValue();
        this.resetValue(values);
      });
    }
  };

  parseAccount = (data) => {
    const arr = [];
    if (!data.account) return [];
    for (const keyName in data.account) {
      arr.push({
        labelName: keyName,
        value: data.account[keyName] || "",
      });
    }
    return arr;
  };

  render() {
    const spanNum2 = 12;
    const { getFieldDecorator } = this.props.form;
    const { value, phone, email, expand } = this.state;
    const account = this.parseAccount(value);
    const formLayout = { width: "90%", display: "inline-block" };
    return (
      <div>
        <Card type="inner" title={this.commonTitle(value.isEnabled, value.supplierName)}>
          {expand && (
            <div>
              <h3>{messages("supplier-1.key824") /*是否启用该机票供应商：*/}</h3>
              <Row>
                <Col span={12}>
                  <FormItem label="">
                    {getFieldDecorator("enableDomestic", {
                      initialValue: value.enableDomestic || false,
                      valuePropName: "checked",
                    })(
                      <Checkbox disabled={!value.isSupportDomestic} onChange={this.onInputFormChange}>
                        {messages("supplier-1.key825") /*启用国内机票在线预订*/}
                      </Checkbox>
                    )}
                  </FormItem>
                </Col>
                <Col span={12}>
                  <FormItem label="">
                    {getFieldDecorator("enableInternationalRfp", {
                      initialValue: value.enableInternationalRfp || false,
                      valuePropName: "checked",
                    })(
                      <Checkbox disabled={!value.isSupportInternationalRfp} onChange={this.onInputFormChange}>
                        {messages("supplier-1.key826") /*启用国际机票询价*/}
                      </Checkbox>
                    )}
                  </FormItem>
                </Col>
              </Row>
              <br />
              <h3>{messages("supplier-1.key827") /*供应商在线查询预订参数配置：*/}</h3>
              <Row>
                <Col span={24}>
                  {account.map((item, index) => (
                    <Col span={spanNum2}>
                      <FormItem label={item.labelName} style={formLayout}>
                        {getFieldDecorator(item.labelName, {
                          initialValue: item.value || "",
                        })(<Input onChange={this.onInputFormChange} />)}
                      </FormItem>
                    </Col>
                  ))}
                </Col>
              </Row>
              <br />
              <h3>{messages("supplier-1.key828") /*供应商客服电话配置：*/}</h3>
              <Row>
                <Col span={19}>
                  <Row style={{ paddingBottom: 30 }} className="platform-common-class">
                    {phone.map((item, index) => (
                      <Col span={spanNum2} style={{ marginTop: index > 1 ? 12 : 0 }}>
                        <FormItem label={messages("supplier-1.key353") /* 客服电话*/ + (index + 1)} style={formLayout}>
                          {getFieldDecorator(`serverPhone${index}`, {
                            initialValue: item || "",
                          })(<Input onChange={this.onInputFormChange} />)}
                        </FormItem>
                        <Icon
                          onClick={() => this.onAddPhoneNumber(index)}
                          type={index != 0 ? "minus-circle" : "plus-circle"}
                          className="plus-icon"
                        />
                      </Col>
                    ))}
                  </Row>
                </Col>
              </Row>
              <h3>{messages("supplier-1.key829") /*供应商客服邮箱配置：*/}</h3>
              <Row>
                <Col span={19}>
                  <Row style={{ paddingBottom: 30 }} className="platform-common-class">
                    {email.map((item, index) => (
                      <Col span={spanNum2} style={{ marginTop: index > 1 ? 12 : 0 }}>
                        <FormItem label={messages("supplier-1.key354") /* 客服邮箱*/ + (index + 1)} style={formLayout}>
                          {getFieldDecorator(`serverEmail${index}`, {
                            initialValue: item || "",
                          })(<Input onChange={this.onInputFormChange} />)}
                        </FormItem>
                        <Icon
                          onClick={() => this.onAddEmail(index)}
                          type={index != 0 ? "minus-circle" : "plus-circle"}
                          className="plus-icon"
                        />
                      </Col>
                    ))}
                  </Row>
                </Col>
              </Row>
              <h3>{messages("supplier-1.key830") /*供应商权重系数配置：*/}</h3>
              <Row>
                <Col span={19}>
                  {
                    <FormItem style={formLayout}>
                      {getFieldDecorator("qualityWeightCoefficient", {
                        initialValue: value.qualityWeightCoefficient || 5,
                      })(<InputNumber onChange={this.onInputFormChange} />)}
                    </FormItem>
                  }
                </Col>
              </Row>
              <br />
            </div>
          )}
        </Card>
      </div>
    );
  }
}

export default AirCardForm;
